package com.lytis.zoovideo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lytis.zoovideo.common.R;
import com.lytis.zoovideo.entity.*;
import com.lytis.zoovideo.entity.vo.TypeVideoVo;
import com.lytis.zoovideo.entity.vo.VideoVo;
import com.lytis.zoovideo.service.VideoEnshrineUserService;
import com.lytis.zoovideo.service.VideoLikesUserService;
import com.lytis.zoovideo.service.VideoService;
import com.lytis.zoovideo.service.VideoTypeService;
import com.lytis.zoovideo.utils.FrameGrabberKit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author :DongPeiLei
 * @description :
 * @create :2022-05-31 18:35:00
 */
@RestController
@RequestMapping("/video")
@CrossOrigin
public class VideoController {
    @Autowired
    private VideoService videoService;
    @Autowired
    private VideoTypeService typeService;
    @Autowired
    private VideoLikesUserService likesUserService;
    @Autowired
    private VideoEnshrineUserService enshrineUserService;

    /*创建分类*/
    @PostMapping("type")
    public R createVideoType(@RequestBody VideoType type) {
        boolean save = typeService.save(type);
        if (save) {
            return R.ok().message("创建分类成功");
        } else {
            return R.error().message("创建分类失败,请检查分类信息");
        }
    }

    /*获取分类子列表*/
    @GetMapping("type/{id}")
    public R getFirstVideoType(@PathVariable("id") Integer id) {
        QueryWrapper<VideoType> wrapper = new QueryWrapper<>();
        wrapper.eq("superior", id);
        List<VideoType> typeList = typeService.list(wrapper);
        return R.ok().data("typeList", typeList).message("获取分类成功");
    }

    /*判断是否为叶子节点*/
    @GetMapping("type/isLeaf/{id}")
    public R judgeIsLeaf(@PathVariable("id") Integer id) {
        QueryWrapper<VideoType> wrapper = new QueryWrapper<>();
        wrapper.eq("superior", id);
        List<VideoType> isLeaf = typeService.list(wrapper);
        return R.ok().data("isLeaf", isLeaf.isEmpty()).message("是否为叶子判断");
    }

    /*创建视频*/
    @PostMapping
    public R createVideo(@RequestBody Video video) {
        System.out.println(video);
        if (StringUtils.isNotBlank(video.getVideoPath())) {
            if (StringUtils.isNotBlank(video.getCoverPath())) {
                boolean save = videoService.save(video);
                return save ? R.ok().message("上传成功") : R.error().message("上传失败");
            } else {
                String baseUrl = "F:\\大三\\项目实践课\\zooLivingDesign\\zooVideo\\src\\main\\resources\\static";
                String imgServerUrl = UUID.randomUUID().toString() + ".jpg";
                String imgUrl = baseUrl + "\\jpg\\" + imgServerUrl;
                String videoPath = video.getVideoPath();
                String videoFullPath = videoPath.substring(videoPath.lastIndexOf(".") + 1) + "\\" + videoPath;
                FrameGrabberKit.getVideoImg(baseUrl + "\\" + videoFullPath, imgUrl);
                video.setCoverPath(imgServerUrl);
                boolean save = videoService.save(video);
                return save ? R.ok().message("上传成功") : R.error().message("上传失败");
            }
        } else {
            return R.error().message("无视频信息，请上传视频");
        }
    }

    /*通过Id获取视频*/
    @GetMapping("/{id}")
    public R getVideoById(@PathVariable Integer id) {
        Video video = videoService.getById(id);
        if (video != null) {
            video.setViews(video.getViews() + 1);
            UpdateWrapper<Video> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", video.getId());
            videoService.update(video, updateWrapper);
            /*获取点赞用户列表*/
            QueryWrapper<VideoLikesUser> likesUserQueryWrapper = new QueryWrapper<VideoLikesUser>();
            likesUserQueryWrapper.eq("video_id", video.getId());
            List<Integer> likedUserList = new ArrayList<>();
            for (VideoLikesUser likesUser : likesUserService.list(likesUserQueryWrapper)) {
                likedUserList.add(likesUser.getUserId());
            }
            /*获取收藏用户列表*/
            QueryWrapper<VideoEnshrineUser> EnshrineUserQueryWrapper = new QueryWrapper<VideoEnshrineUser>();
            EnshrineUserQueryWrapper.eq("video_id", video.getId());
            List<Integer> enshrinedUserList = new ArrayList<>();
            for (VideoEnshrineUser likesUser : enshrineUserService.list(EnshrineUserQueryWrapper)) {
                enshrinedUserList.add(likesUser.getUserId());
            }
            VideoVo videoVo = new VideoVo(video);
            videoVo.setLikedUserList(likedUserList);
            videoVo.setEnshrinedUserList(enshrinedUserList);
            return R.ok().data("video", videoVo);
        }
        return R.error().message("视频不存在");
    }

    /*获取视频列表*/
    @GetMapping
    public R getVideoListByPage(@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "sort", defaultValue = "views") String sort) {
        Page<Video> videoPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(sort);
        videoPage = videoService.page(videoPage, queryWrapper);
        return R.ok().data("total", videoPage.getTotal()).data("results", videoPage.getRecords());
    }

    /*收藏*/
    @PostMapping("/enshrine")
    @Transactional
    public R publishEnshrine(@RequestBody Video video) {
        QueryWrapper<VideoEnshrineUser> EnshrineWrapper = new QueryWrapper<>();
        EnshrineWrapper.eq("user_id", video.getUserId()).eq("video_id", video.getId());
        VideoEnshrineUser record = enshrineUserService.getOne(EnshrineWrapper);
        QueryWrapper<Video> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("id", video.getId());
        if (record != null) {
            enshrineUserService.removeById(record);
            video.setEnshrine(video.getEnshrine() - 1);
            videoService.update(video, videoWrapper);
            return R.ok().message("取消收藏成功");
        } else {
            VideoEnshrineUser assUser = new VideoEnshrineUser();
            assUser.setUserId(video.getUserId());
            assUser.setVideoId(video.getId());
            enshrineUserService.save(assUser);
            video.setEnshrine(video.getEnshrine() + 1);
            videoService.update(video, videoWrapper);
            return R.ok().message("收藏成功");
        }
    }

    /*点赞*/
    @PostMapping("/like")
    @Transactional
    public R publishLikes(@RequestBody Video video) {
        QueryWrapper<VideoLikesUser> LikesWrapper = new QueryWrapper<>();
        LikesWrapper.eq("user_id", video.getUserId()).eq("video_id", video.getId());
        VideoLikesUser record = likesUserService.getOne(LikesWrapper);
        QueryWrapper<Video> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("id", video.getId());
        if (record != null) {
            likesUserService.removeById(record);
            video.setLikes(video.getLikes() - 1);
            videoService.update(video, videoWrapper);
            return R.ok().message("取消点赞成功");
        } else {
            VideoLikesUser assUser = new VideoLikesUser();
            assUser.setUserId(video.getUserId());
            assUser.setVideoId(video.getId());
            likesUserService.save(assUser);
            video.setLikes(video.getLikes() + 1);
            videoService.update(video, videoWrapper);
            return R.ok().message("点赞成功");
        }
    }

    /*获取视频详细信息*/
    @GetMapping("/typeWithVideo")
    public R getTypeWithVideoInfo() {
        QueryWrapper<VideoType> typeQueryWrapper = new QueryWrapper<>();
        typeQueryWrapper.eq("superior", 0);
        List<TypeVideoVo> typeVideoVos = new ArrayList<>();
        for (VideoType videoType : typeService.list(typeQueryWrapper)) {
            TypeVideoVo vo = new TypeVideoVo();
            vo.setId(videoType.getId());
            vo.setLabel(videoType.getLabel());
            QueryWrapper<VideoType> wrapper = new QueryWrapper<>();
            wrapper.eq("superior", videoType.getId());
            List<VideoType> isLeaf = typeService.list(wrapper);
            QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
            if (isLeaf.isEmpty()) {
                videoQueryWrapper.eq("type", videoType.getId());
                vo.setChildren(new ArrayList<>());
            } else {
                List<Integer> idList = new ArrayList<>();
                vo.setChildren(isLeaf);
                for (VideoType type : isLeaf) {
                    idList.add(type.getId());
                }
                videoQueryWrapper.in("type", idList);
            }
            List<Video> videoList = videoService.list(videoQueryWrapper);
            vo.setVideos(videoList);
            typeVideoVos.add(vo);
        }
        return R.ok().data("typeList", typeVideoVos);
    }

    /*根据分类Id获取视频详细信息*/
    @GetMapping("/typeWithVideo/{id}")
    public R getTypeWithVideoInfoById(@PathVariable Integer id,
                                      @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum
    ) {
        VideoType videoType = typeService.getById(id);
        if (videoType != null) {
            QueryWrapper<VideoType> wrapper = new QueryWrapper<>();
            wrapper.eq("superior", videoType.getId());
            List<VideoType> isLeaf = typeService.list(wrapper);
            QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
            if (isLeaf.isEmpty()) {
                videoQueryWrapper.eq("type", videoType.getId());
            } else {
                List<Integer> idList = new ArrayList<>();
                for (VideoType type : isLeaf) {
                    idList.add(type.getId());
                }
                videoQueryWrapper.in("type", idList);
            }
            Page<Video> page = new Page<>(pageNum, pageSize);
            videoService.page(page, videoQueryWrapper);
            return R.ok().data("typeInfo", videoType).data("videoList", page.getRecords()).data("total", page.getTotal());
        } else {
            return R.error().message("分类不存在");
        }
    }
}
